package com.hp.service;

import com.hp.dao.*;
import com.hp.entity.*;
import com.hp.entity.dto.RegistryDto;
import com.hp.entity.dto.RoomDto;
import com.hp.utils.Page;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class RegistryService {
    private RegistryDao registryDao=new RegistryDao();
    private DepartmentDao departmentDao=new DepartmentDao();
    private PatientDao patientDao=new PatientDao();
    private UserDao userDao=new UserDao();
    private RoomDao roomDao=new RoomDao();
    public boolean addRegistry(Registry registry){

        return registryDao.addRegistry(registry);
    }

    public Page<RegistryDto> getRegistryListByPage(Map<String, Object> map){
        Page<RegistryDto> page=new Page<>();
        List<Registry> list= registryDao.getRegistryListByPage(map);
        Long total=registryDao.totalRegistry(map);
        page.setTotal(total);

        List<RegistryDto> registryDtoList=new ArrayList<>();
        list.stream().forEach(p->{
            RegistryDto dto=new RegistryDto();
            try {
                DateConverter converter = new DateConverter();
                converter.setPattern(new String("yyyy-MM-dd"));
                ConvertUtils.register(converter, Date.class);
                //拷贝数据
                BeanUtils.copyProperties(dto,p);

                Department department=departmentDao.getDepartmentById(p.getDepartmentId());
                Patient patient=patientDao.getPatientById(p.getPatientId());
                User user=userDao.getUserById(p.getUserId());
                Room room= roomDao.getRoom(p.getRoomId());

                //数据脱敏处理
                user.setPassword(null);
                user.setSalt(null);

                dto.setDepartment(department);
                dto.setPatient(patient);
                dto.setUser(user);
                dto.setRoom(room);

                registryDtoList.add(dto);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        });
        page.setList(registryDtoList);
        return page;

    }

    public boolean updateRegistryStatus(Registry registry) {
        return registryDao.updateRegistryStatus(registry);
    }
}
